//
//  liveCenterViewController.m
//  FKGW
//
//  Created by song ce on 2017/3/1.
//  Copyright © 2017年 song ce. All rights reserved.


#import "liveCenterViewController.h"
#import "ZhiboShopCell.h"
#import "SmallView.h"
#import "SelectedEntryView.h"
#import "Hongbao.h"
#import "ChatTableViewCell.h"
#import <AliyunPlayerSDK/AliyunPlayerSDK.h>
#import <MediaPlayer/MediaPlayer.h>
#import "AFNetworking.h"
#import "MBProgressHUD.h"
#import "EaseSDKHelper.h"
#import "PrivateLetterViewController.h"

//友盟推送
#define  UMAPPKEY @"58d0dada766613201e000fba"
#define UMAppMasterSecret  @"qyphajz62z0fagsjch2cxsjspkf5x1mw"


@interface liveCenterViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *tableV;//显示商品列表
@property (weak, nonatomic) IBOutlet UIButton *closeButton;//右上角关闭按钮
@property (weak, nonatomic) IBOutlet UIImageView *view1;//以下三个视图的背景视图
@property (weak, nonatomic) IBOutlet UIImageView *shopIconImageV;//店铺头像
@property (weak, nonatomic) IBOutlet UILabel *shopNameLabel;//店铺名称
@property (weak, nonatomic) IBOutlet UILabel *lookCountLabel;//在线观看人数
@property (weak, nonatomic) IBOutlet UIImageView *view2;//关注按钮背景视图
//右上角自左向右显示4个用户头像
@property (weak, nonatomic) IBOutlet UIImageView *icon1;//用户1
@property (weak, nonatomic) IBOutlet UIImageView *icon2;//用户2
@property (weak, nonatomic) IBOutlet UIImageView *icon3;//用户3
@property (weak, nonatomic) IBOutlet UIImageView *icon4;//用户4
@property (weak, nonatomic) IBOutlet UILabel *hongbaoCountLabel;//红包数量
@property (weak, nonatomic) IBOutlet UIButton *hongbaoButton;//红包按钮
@property (strong, nonatomic) IBOutlet UIButton *escButton;//全屏按钮
@property (weak, nonatomic) IBOutlet UILabel *goodsCountLabel;//左下角商店商品数量
@property(nonatomic,strong)SelectedEntryView *entryView;//选择员工直播入口视图
@property(nonatomic,strong)Hongbao *hongbaoView;//红包视图
@property(nonatomic,strong) UIImageView *imageV;//暂时代替直播视图
@property(nonatomic,strong) UIView *playView;//直播视图
@property (weak, nonatomic) IBOutlet UILabel *shareCountLabel;//显示分享次数
@property (weak, nonatomic) IBOutlet UITableView *chatView;
@property (nonatomic, strong) AliVcMediaPlayer* player;

@property(nonatomic,copy)NSString *huanxinUserName;

@end

@implementation liveCenterViewController
-(instancetype)init{
    self = [super init];
    if(self){
        //监听应用进入后台
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(EnterBackGroundPauseVideo) name:UIApplicationWillResignActiveNotification object:nil];
        //监听应用回到前台
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(EnterForeGroundPlayVideo) name:UIApplicationDidBecomeActiveNotification object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardWillShowNotification object:nil];
         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardWillHideNotification object:nil];

        }
    return self;
}

//视图已经出现，让表格滚到最低端
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [IQKeyboardManager sharedManager].keyboardDistanceFromTextField = 0;

    if(self.isDianBo) return;
    [self scrollBottom];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    [IQKeyboardManager sharedManager].keyboardDistanceFromTextField = 10.0f;
}

- (void)scrollBottom{
    NSIndexPath *lastIndexPath=[NSIndexPath indexPathForRow:self.chatArray.count-1 inSection:0];
    //让某一个单元格滚动到一个位置
    [self.chatView scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //播放视频
//    [self playVideo];
    
    if(!self.isDianBo){
        //聊天内容数组
        self.chatArray = [NSMutableArray array];
        //设置红包数量Label的圆角
        self.hongbaoCountLabel.layer.cornerRadius =9;
        self.hongbaoCountLabel.layer.masksToBounds = YES;
        self.hongbaoCountLabel.alpha = .8;

        [self testData];
        //显示聊天内容
        self.chatView.delegate = self;
        self.chatView.dataSource = self;
        self.chatView.backgroundColor = [UIColor clearColor];
        self.chatView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.chatView.showsVerticalScrollIndicator = NO;

    }else{
        [self.hongbaoCountLabel removeFromSuperview];
        [self.hongbaoButton removeFromSuperview];
        [self.chatView removeFromSuperview];
        [self.icon1 removeFromSuperview];
        [self.icon2 removeFromSuperview];
        [self.icon3 removeFromSuperview];
        [self.icon4 removeFromSuperview];
        [self aboutDianboView];
    }
    //移除自定义的navigtionBar;
    [self.naviBar removeFromSuperview];
    //设置商品数量label的圆角
    self.goodsCountLabel.layer.cornerRadius = 6.5;
     self.goodsCountLabel.layer.masksToBounds = YES;
      //设置店铺名称、关注按钮的背景视图圆角
    self.view1.layer.cornerRadius =18.5;
    self.view1.layer.masksToBounds = YES;
    self.view2.layer.cornerRadius =12.5;
    self.view2.layer.masksToBounds = YES;
    self.view2.userInteractionEnabled = YES;
    self.shareCountLabel.layer.cornerRadius = 6;
    self.shareCountLabel.layer.masksToBounds = YES;

    //这个临时的到时候要注释掉
    _imageV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 20, Main_Screen_Width, Main_Screen_Height)];
    _imageV.image = [UIImage imageNamed:@"photo_bg"];
    _imageV.userInteractionEnabled = YES;
    [self.view addSubview:_imageV];
    [self.view insertSubview:_imageV atIndex:0];
    
    self.view.userInteractionEnabled = YES;
    self.view.backgroundColor = [UIColor blackColor];
    
        //显示商品的列表
    [self tableViewAndHeaderView];
    
    //监测网路的状态
    [self  networkReachability];
    
    //加入聊天室
    
    //获取当前环信用户的昵称
    NSString *  ephone = [NSString stringWithFormat:@"%@0",USERPHONE];
    [self loadUserName:ephone];
    
    //添加聊天内容输入框
    [self.view addSubview:self.toolBar];
}


//新建播放器
-(void) playVideo
{
    //新建播放器
    self.player = [[AliVcMediaPlayer alloc] init];
    //创建播放器，传入显示窗口
    [self.player create:self.playView];
    //调用prepareToPlay成功通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(OnVideoPrepared:) name:AliVcMediaPlayerLoadDidPreparedNotification object:self.player];
    //调用prepareToPlay失败通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(OnVideoError:) name:AliVcMediaPlayerPlaybackErrorNotification object:self.player];
    //调用stop/reset成功后播  自动播放结束也会发送
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(OnVideoFinish:)
                                                 name:AliVcMediaPlayerPlaybackDidFinishNotification object:self.player];
    //传入播放地址，初始化视频，准备播放
    [self.player prepareToPlay:[NSURL URLWithString:self.remoteUrl]];
    //开始播放
    [self.player play];
}
-(void)testData{
    NSArray *arr = @[@"01kajfkkkl经典款礼服考虑双方都加快了 akklsdfjklsjfkld",
                     @"02kajfkkkl经典款礼服考虑双方都加快了 ",
                     @"03kajfkkkl经典款礼服考虑双方都加快了 akklsdfjklsjfkld",
                     @"04kajfkkkl经典款礼服考虑双方都加快了 akklsdfjklsjfkld",
                     @"05kajfkkklakklsdfjklsjfkld",
                     @"06kajfkkklakkl上的索科洛夫健康啦司法解释了；高科技啊老师；可大幅减少对肌肤来说都加快了sdfjklsjfkld",
                     @"07kajfkkklakklsdfjklsjfkld",
                     @"08kajfkkklakklsdfjklsjfkld",
                     ];
    for(int i=0;i<arr.count;i++){
        ChatModel * model = [[ChatModel alloc]init];
        model.content = arr[i];
        [self.chatArray addObject:model];
        
    }
}
//关注按钮
- (IBAction)guanzhu:(UIButton *)sender {
    sender.selected = !sender.selected;
    if(sender.isSelected){
        [sender setImage:[UIImage imageNamed:@"icon_guanzhui_sel"] forState:UIControlStateNormal];
    }else{
        [sender setImage:[UIImage imageNamed:@"zb_guanzhu"] forState:UIControlStateNormal];
    }
}
//关闭直播页面
- (IBAction)close:(UIButton *)sender {
    [self.view resignFirstResponder];
    //停止当前视频播放
    [self.player stop];
    //销毁播放器
    [self.player destroy];
    //退出播放界面
//    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

//抢红包
- (IBAction)qianghongbao:(UIButton *)sender {
    UIWindow *window = (UIWindow*)[UIApplication sharedApplication].keyWindow;
    //添加遮罩视图
    [window addSubview:self.maskV];
    //添加红包视图
    [window addSubview:self.hongbaoView];
    //打开遮罩视图的手势交互
    self.maskV.userInteractionEnabled = YES;
    __weak typeof (self) weakSelf = self;
    //点击红包视图左上角的关闭按钮回调处理
    _hongbaoView.closeBlock=^{
        [weakSelf.maskV removeFromSuperview];
        [weakSelf.hongbaoView removeFromSuperview];
    };
}
//左下角商店按钮
- (IBAction)shop:(UIButton *)sender {
      __weak typeof (self) weakSelf = self;
    [UIView animateWithDuration:.5 animations:^{
        CGFloat with =Main_Screen_Width*0.373;
        [weakSelf hiddenSomeView];
        weakSelf.imageV.frame = CGRectMake((Main_Screen_Width-with)/2, 20, with, with*1.714);
        self.tableV.frame = CGRectMake(0, self.imageV.bottom, Main_Screen_Width, Main_Screen_Height-self.imageV.bottom);
        [weakSelf addSomeView];
    }];
}
//直播页面从小恢复到全屏按钮
- (IBAction)escTobigV:(UIButton *)sender {
    __weak typeof (self) weakSelf = self;
    [UIView animateWithDuration:.5 animations:^{
        //显示一些页面
        [weakSelf showSomeView];
        //移除一些页面
        [weakSelf removeSomeView];
        //改变直播页面的frame
        weakSelf.imageV.frame = CGRectMake(0, 20, Main_Screen_Width, Main_Screen_Height);
        //改变现实商品的视图的frame
        weakSelf.tableV.frame = CGRectMake(0, Main_Screen_Height, Main_Screen_Width, 0);
    }];
}
//聊天视图的显示和隐藏
- (IBAction)showOrHidden:(UIButton *)sender {
    sender.selected = !sender.selected;
    if(sender.selected){
        self.chatView.hidden = YES;
    }else{
        self.chatView.hidden = NO;
    }
}

//直播页面缩小的时候添加一些视图
-(void)addSomeView{
    self.escButton.top = self.imageV.bottom-10-60;
    self.escButton.left = self.imageV.left-70;
    [self.view addSubview:self.escButton];
    
    CGFloat  height =   (Main_Screen_Width*0.373*1.714-self.closeButton.bottom-20);
    SmallView *v1=[[[NSBundle mainBundle]loadNibNamed:@"SmallView" owner:self options:nil]lastObject];
    v1.left =Main_Screen_Width- (self.imageV.left-10);
    v1.bottom= self.imageV.bottom;
    v1.width =self.imageV.left-10;
    CGFloat  h=0;
    for(int i=0;i<3;i++){
        if(height-h<57)  return;
        SmallView *v1=[[[NSBundle mainBundle]loadNibNamed:@"SmallView" owner:self options:nil]lastObject];
        v1.tag=i+1000;
        v1.left =Main_Screen_Width- (self.imageV.left-10);
         v1.width =self.imageV.left-10;
         v1.bottom= self.imageV.bottom-(v1.height+5)*i;
        [self.view addSubview:v1];
        h = 62*(i+1);
    }
}

- (void)removeSomeView{
    [self.escButton removeFromSuperview];
    for(int i=0;i<3;i++){
        SmallView *v1= [self.view viewWithTag:i+1000];
        [v1 removeFromSuperview];
    }
}

- (void)tableViewAndHeaderView{
    //表视图
    _tableV = [[UITableView alloc]initWithFrame:CGRectMake(0, Main_Screen_Height, Main_Screen_Width,100) style:UITableViewStyleGrouped];
    _tableV.showsVerticalScrollIndicator = NO;
    _tableV.backgroundColor = [UIColor colorWithRed:242./255 green:242./255 blue:242./255 alpha:1.];
    _tableV.delegate = self;
    _tableV.dataSource =self;
    [self.view addSubview:_tableV];
    _tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;    {
    if([tableView isEqual:self.chatView]){
        return 1;
    }
    return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //    return self.dataSource.count;
    if([tableView isEqual:self.chatView]){
        return self.chatArray.count;
    }
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if([tableView isEqual:self.chatView]){
        NSString *ident=@"ChatTableViewCell";
        ChatTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:ident];
        if(cell==nil){
            cell=[[[NSBundle mainBundle]loadNibNamed:@"ChatTableViewCell" owner:self options:nil]lastObject];
            ChatModel *model = self.chatArray[indexPath.row];
            cell.model = model;
        }
        //       cell.model = self.dataSource[indexPath.row];
        return cell;
    }
    NSString *ident=@"actell";
    ZhiboShopCell *cell=[tableView dequeueReusableCellWithIdentifier:ident];
    if(cell==nil){
        cell=[[[NSBundle mainBundle]loadNibNamed:@"ZhiboShopCell" owner:self options:nil]lastObject];
    }
    //       cell.model = self.dataSource[indexPath.row];
    //推荐直播处理
    __weak typeof(self) weakSelf = self;
    cell.recommendLiveBlock = ^{
        NSString *userName ;
        if(weakSelf.huanxinUserName.length){
            userName = weakSelf.huanxinUserName;
        }else{
            userName =[NSString stringWithFormat:@"%@0",USERPHONE];
        }
        NSDictionary *custom = @{
                                 @"userName":userName,
                                 @"goodImage":@"goodImage",
                                 @"goodName":@"goodName"
                                 };
        [weakSelf recommendPushWithGoodInfo:custom];
    };
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if([tableView isEqual:self.chatView]){
         ChatModel *model = self.chatArray[indexPath.row];
        CGRect frame = [model.content boundingRectWithSize:CGSizeMake(self.chatView.width, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil];
            CGFloat height = CGRectGetHeight(frame);
        return height;
    }
    return 98;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;{
    if([tableView isEqual:self.chatView]){
        return 0;
    }
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;{
    if([tableView isEqual:self.chatView]){
        return 0;
    }
    return 1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
}

//点击左上角的头像事件
- (IBAction)touxiangButton:(UIButton *)sender {
    UIWindow *window = (UIWindow*)[UIApplication sharedApplication].keyWindow;
      [window addSubview:self.maskV];
     [window addSubview:self.entryView];
    //设置遮罩视图可以响应事件
    self.maskV.userInteractionEnabled = YES;
    __weak typeof (self) weakSelf = self;
    //选择直播员工页面的关闭按钮回调处理
    _entryView.closeBlock=^{
        [weakSelf.maskV removeFromSuperview];
        [weakSelf.entryView removeFromSuperview];
    };
}
//底部按钮事件
//分享
- (IBAction)share:(UIButton *)sender {
    
}
//聊天
- (IBAction)chat:(UIButton *)sender {
    [self.smallTextField becomeFirstResponder];

}
//私信
- (IBAction)message:(UIButton *)sender {
    PrivateLetterViewController *private = [[PrivateLetterViewController alloc]init];
    private.vcName = @"私信";
    private.isPush = YES;
    [self.navigationController pushViewController:private animated:YES];
}

- (IBAction)both:(UIButton *)sender {
    
}

//店铺公告
- (IBAction)guangbo:(UIButton *)sender {
    
}

#pragma mark - 设置状态栏
- (UIStatusBarStyle)preferredStatusBarStyle {
           return UIStatusBarStyleLightContent;
}

#pragma mark - 懒加载视图
//红包视图
- (Hongbao *)hongbaoView{
    if(_hongbaoView==nil){
        _hongbaoView =[[[NSBundle mainBundle]loadNibNamed:@"Hongbao" owner:self options:nil]lastObject];
        CGFloat with =Main_Screen_Width*0.8;
        CGFloat height = with*1.067;
        _hongbaoView.width = with;
        _hongbaoView.height = height;
        _hongbaoView.centerX = Main_Screen_Width/2;
        _hongbaoView.centerY = self.view.centerY;
    }
    return _hongbaoView;
}
//点击左上角的头像选择入口的视图
- (SelectedEntryView *)entryView{
    if(_entryView==nil){
        _entryView =[[[NSBundle mainBundle]loadNibNamed:@"SelectedEntryView" owner:self options:nil]lastObject];
        _entryView.centerX = Main_Screen_Width/2;
        _entryView.centerY = self.view.centerY;
    }
    return _entryView;
}

//直播视图
-(UIView *)playView{
    if(_playView==nil){
        _playView = [[UIView alloc]initWithFrame:CGRectMake(0, 20, Main_Screen_Width, Main_Screen_Height)];
        [self.view addSubview:_playView];
        [self.view insertSubview:_playView atIndex:0];
    }
    return _playView;
}

- (void)hiddenSomeView{
    self.icon1.hidden = YES;
    self.icon2.hidden = YES;
    self.icon3.hidden = YES;
    self.icon4.hidden = YES;
    self.hongbaoButton.hidden = YES;
    self.hongbaoCountLabel.hidden = YES;
}
- (void)showSomeView{
    self.icon1.hidden = NO;
    self.icon2.hidden = NO;
    self.icon3.hidden = NO;
    self.icon4.hidden = NO;
    self.hongbaoButton.hidden = NO;
    self.hongbaoCountLabel.hidden = NO;
}


//-----------********播放器相关的通知事件*******----------
//调用prepareToPlay成功
-(void)OnVideoPrepared:(NSNotification*)noti{
    DLog(@"调用prepareToPlay成功---%@",noti.object);
}
//调用prepareToPlay成功
-(void)OnVideoError:(NSNotification*)noti{
     DLog(@"调用prepareToPlay失败---%@",noti.object);
}
 //调用stop/reset成功后播  自动播放结束也会发送
-(void)OnVideoFinish:(NSNotification*)noti{
    DLog(@"播放结束---%@",noti.object);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//进入后台
-(void) EnterBackGroundPauseVideo
{
    if(self.player && [self.player isPlaying]) {
        [self.player pause];
    }
}

//回到前台
-(void) EnterForeGroundPlayVideo
{
    if(self.player && ![self.player  isPlaying]) {
        [self.player play];
        }
    if(!self.player){
        [self playVideo];
    }
}

//点播相关控制视图
-(void)aboutDianboView{
    
    
    
    
}

#pragma mark - 网络状态监测
- (void)networkReachability{
    AFNetworkReachabilityManager *manager =[AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWiFi:
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                [MBProgressHUD showTipMessageInWindow:@"您当前处于移动网路，请注意流量消耗～"];
                break;
            case AFNetworkReachabilityStatusNotReachable:
                //Wi-Fi和移动数据已断开
                [MBProgressHUD showTipMessageInWindow:@"Wi-Fi和移动数据已断开"];
                break;
            case AFNetworkReachabilityStatusUnknown:
                break;
            default:
                break;
        }
    }];
    [manager startMonitoring];
}
#pragma mark --加入聊天室
//加入聊天室
-(void)joinChatRoom{
     [[EMClient sharedClient].roomManager joinChatroom:self.chatRoomId completion:^(EMChatroom *aChatroom, EMError *aError) {
         if(aError==nil){
             DLog(@"加入聊天室success");
         }else{
             DLog(@"加入聊天室failed");
         }
    }];
}

#pragma mark -- 离开聊天室
-(void)leaveChatRoom{
    [[EMClient sharedClient].roomManager leaveChatroom:self.chatRoomId completion:^(EMError *aError) {
        if(aError==nil){
            DLog(@"离开聊天室success");
        }else{
            DLog(@"离开聊天室failed");
        }
    }];
    [[EMClient sharedClient].chatManager deleteConversation:self.chatRoomId isDeleteMessages:YES completion:nil];

}


//获取正在聊天的内容


#pragma mark --获取用户环信昵称
//获取用户昵称
-(void)loadUserName:(NSString*)userId{
    NSMutableArray *userNames = [NSMutableArray arrayWithObject:userId];
    NSData *pramasData = [NSJSONSerialization dataWithJSONObject:userNames options:NSJSONWritingPrettyPrinted error:nil];
    NSString *userName = [[NSString alloc]initWithData:pramasData encoding:NSUTF8StringEncoding];
    NSDictionary *paramDic = @{@"userName":userName};
    //2.68获取聊天对象信息接口
    __weak typeof(self) weakSelf = self;
    [Tools AFNetworkingRequestTypePostWithUrl:GETCHATOBJECTSINFORMATION paramters:paramDic afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"//获取聊天对象信息接口----%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSArray *listArr = resultDic[@"data"];
            if([listArr isKindOfClass:[NSNull class]]){
                return ;
            }
            NSDictionary *dic = listArr.lastObject;
            NSString *nickName =dic[@"nickName"];
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.huanxinUserName = nickName;
            });
        }else{
            DLog(@"获取环信昵称失败");
        }
    }];
}

#pragma mark -- 推荐直播通过友盟发送通知
-(void)recommendPushWithGoodInfo:(NSDictionary*)custom{
    NSDictionary *aps = @{
                          @"alert":@"",
                          @"custom":custom
                          };
    NSDictionary *payload = @{
                              @"aps":aps,
                              };
    NSString *device_tokens;
    NSTimeInterval time = (int)[[NSDate date] timeIntervalSince1970];
    NSString *timestamp = [NSString stringWithFormat:@"%f",time];
    timestamp = [timestamp substringToIndex:10];
    DLog(@"%@",timestamp);
    NSDictionary *params = @{
                             @"appkey":UMAPPKEY,
                             @"timestamp":timestamp,
                             @"device_tokens":device_tokens,
                             @"type":@"unicast",
                             @"payload":payload
                             };
    NSData *pramasData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
    NSString *paramStr = [[NSString alloc]initWithData:pramasData encoding:NSUTF8StringEncoding];
    NSString *sign = [NSString stringWithFormat:@"%@%@%@%@",@"POST",UMPUSHHTTPS,paramStr,UMAppMasterSecret];
    sign= [Tools MD5:sign];
    NSString *url = [NSString stringWithFormat:@"%@?sign=%@",UMPUSHHTTPS,sign];
   [Tools AFNetworkingRequestTypePostWithUrl:url paramters:nil afterResultBlock:^(NSDictionary *resultDic) {
       if([resultDic[@"ret"] isEqualToString:@"SUCCESS"]){
           DLog(@"推送内容向友盟发送成功");
       }else{
           NSDictionary *data = resultDic[@"data"];
           DLog(@"推送失败--错误代码-%@",data[@"error_code"]);
       }
   }];
}
//底部工具栏
- (UIToolbar *)toolBar{
    if(_toolBar==nil){
        _toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, Main_Screen_Height, Main_Screen_Width, 44)];
        //创建按钮
        UIButton *doneButton = [UIButton buttonWithType:0];
        doneButton.frame = CGRectMake(0, 0, 60, 44);
        [doneButton setTitle:@"发送" forState:UIControlStateNormal];
        [doneButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        doneButton.titleLabel.font = [UIFont systemFontOfSize:15];
        [doneButton addTarget:self action:@selector(toolBarButtonDidClicked) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *item1 = [[UIBarButtonItem alloc]initWithCustomView:doneButton];
        UIBarButtonItem *item2 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:
                                  UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        UIBarButtonItem *item3 = [[UIBarButtonItem alloc]initWithCustomView:self.chatTextField];
        _toolBar.items = @[item3,item2,item1];
    }
    return _toolBar;
}

//toolBar的完成按钮点击事件
- (void)toolBarButtonDidClicked{
    [self.view endEditing:NO];
    if(!self.chatTextField.text.length) return;
    //构造文字消息
    EMMessage *message = [EaseSDKHelper sendTextMessage:self.chatTextField.text
                                                     to:self.conversation.conversationId
                                            messageType:EMChatTypeChatRoom
                                             messageExt:nil];
    //发送消息
    __weak typeof(self) weakself = self;
    [[EMClient sharedClient].chatManager sendMessage:message progress:^(int progress) {
        
    } completion:^(EMMessage *aMessage, EMError *aError) {
        if (!aError) {
            
        }else {
           
        }
    }];
}
-(UITextField *)chatTextField{
    if(_chatTextField==nil){
        _chatTextField = [[UITextField alloc]initWithFrame:CGRectMake(10, 7, Main_Screen_Width-60-10, 30)];
        _chatTextField.placeholder = @"输入点什么...";
    }
    return _chatTextField;
}

#pragma 键盘通知调用方法
- (void)keyBoardShow:(NSNotification *)notif{
    NSValue *value = notif.userInfo[@"UIKeyboardFrameEndUserInfoKey"];
    CGRect frame = [value CGRectValue];
    CGFloat height = frame.size.height;
    DLog(@"-----%f",height);
    if ([notif.name isEqualToString:@"UIKeyboardWillShowNotification"]) {
        self.toolBar.top = Main_Screen_Height-height-40;
        [self.chatTextField becomeFirstResponder];
        self.chatTextField.text = @"";
    }else if ([notif.name isEqualToString:@"UIKeyboardWillHideNotification"]){
        self.toolBar.top = Main_Screen_Height;
    }
}


@end
